import React, { useState } from 'react'
import { Button, Form, Input, NavBar, Toast } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import request from '../../api/request'
import { encryptPassword } from '../../utils/rsa'

export default function ChangePassword() {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)

  const onSubmit = async (values: { oldPwd: string; newPwd: string; confirmPwd: string }) => {
    if (values.newPwd !== values.confirmPwd) {
      Toast.show('两次输入的新密码不一致')
      return
    }
    try {
      setLoading(true)
      const oldPwdEnc = encryptPassword(values.oldPwd)
      const newPwdEnc = encryptPassword(values.newPwd)

      const resp = await request.put('/health/user/verify/v1/updateUserPwd', {
        oldPwd: oldPwdEnc,
        newPwd: newPwdEnc,
      })
      const data = resp?.data || {}
      if (data.status === '0000') {
        Toast.show('修改成功')
        navigate(-1)
      } else {
        Toast.show(data.message || '修改失败')
      }
    } catch (err) {
      Toast.show('网络异常，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div>
      <NavBar onBack={() => navigate(-1)}>修改密码</NavBar>
      <div style={{ padding: 12 }}>
        <Form
          form={form}
          layout='horizontal'
          footer={<Button block color='primary' loading={loading} type='submit'>提交</Button>}
          onFinish={onSubmit}
        >
          <Form.Item name='oldPwd' label='原密码' rules={[{ required: true, message: '请输入原密码' }]}> 
            <Input placeholder='请输入原密码' type='password' clearable />
          </Form.Item>
          <Form.Item name='newPwd' label='新密码' rules={[{ required: true, message: '请输入新密码' }, { min: 6, message: '至少6位' }]}> 
            <Input placeholder='请输入新密码' type='password' clearable />
          </Form.Item>
          <Form.Item name='confirmPwd' label='确认新密码' rules={[{ required: true, message: '请再次输入新密码' }]}> 
            <Input placeholder='请再次输入新密码' type='password' clearable />
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}











